<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="药品名称" prop="drugName">
        <el-input
          v-model="queryParams.drugName"
          placeholder="请输入药品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库日期" prop="incomingDate">
        <el-date-picker clearable
          v-model="queryParams.incomingDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择入库日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:drugIncoming:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:drugIncoming:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:drugIncoming:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:drugIncoming:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="drugIncomingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="入库记录ID" align="center" prop="incomingId" /> -->
      <el-table-column label="药品名称" align="center" prop="drugName" />
      <el-table-column label="药品规格" align="center" prop="drugSpecification" />
      <el-table-column label="入库操作人" align="center">
        <template #default="scope">
          <span>{{ getOperatorName(scope.row.operatorId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库数量" align="center" prop="quantity" />
      <el-table-column label="入库日期" align="center" prop="incomingDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.incomingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商名称" align="center">
        <template #default="scope">
          <span>{{ getSupplierName(scope.row.supplierId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库价格" align="center" prop="price" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:drugIncoming:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:drugIncoming:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品入库信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="drugIncomingRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="药品名称" prop="drugName">
          <el-input v-model="form.drugName" placeholder="请输入药品名称" />
        </el-form-item>
        <el-form-item label="药品规格" prop="drugSpecification">
          <el-input v-model="form.drugSpecification" placeholder="请输入药品规格" />
        </el-form-item>
        <el-form-item label="入库数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入入库数量" />
        </el-form-item>
        <el-form-item label="入库日期" prop="incomingDate">
          <el-date-picker clearable
            v-model="form.incomingDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择入库日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请选择供应商名称" style="width: 70%;" readonly />
          <el-button type="primary" @click="openSupplierSelectDialog" slot="append" style="width: 30%;">选择供应商</el-button>
          <!-- 新增一个隐藏的输入框用于存储供应商 ID -->
          <el-input v-model="form.supplierId" type="hidden" />
        </el-form-item>
        <el-form-item label="入库价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入入库价格" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 选择供应商对话框 -->
    <el-dialog :title="'选择供应商'" v-model="supplierSelectDialogVisible" width="500px" append-to-body>
      <el-table :data="supplierList" @row-click="selectSupplier" style="width: 100%;" stripe>
        <el-table-column prop="supplierName" label="供应商名称" align="center"></el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" align="center"></el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="supplierSelectDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DrugIncoming">
import { listDrugIncoming, getDrugIncoming, delDrugIncoming, addDrugIncoming, updateDrugIncoming } from "@/api/manage/drugIncoming";
import { listUser } from "@/api/system/user";
import { listSuppliers } from "@/api/manage/suppliers";
import { listDrugs, addDrugs } from "@/api/manage/drugs";
import { updateDrugStock, addDrugStock, getDrugStock, listDrugStock } from "@/api/manage/drugStock";
import { addDrugMovements } from "@/api/manage/drugMovements";
import { getInfo } from "@/api/login";

const { proxy } = getCurrentInstance();

const drugIncomingList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const operatorMap = ref({}); // 用于存储操作人 ID 到姓名的映射
const supplierMap = ref({}); // 用于存储供应商 ID 到供应商名称的映射
const supplierList = ref([]); // 存储所有供应商信息
const supplierSelectDialogVisible = ref(false); // 控制供应商选择对话框的显示与隐藏
const currentUserId = ref(null); // 用于存储当前登录用户的 ID

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    incomingId: null,
    drugName: null,
    drugSpecification: null,
    operatorId: null,
    quantity: null,
    incomingDate: null,
    supplierName: null,
    price: null,
    createTime: null,
    updateTime: null
  },
  rules: {
    drugName: [
      { required: true, message: "药品名称不能为空", trigger: "blur" }
    ],
    drugSpecification: [
      { required: true, message: "药品规格不能为空", trigger: "blur" }
    ],
    quantity: [
      { required: true, message: "入库数量不能为空", trigger: "blur" }
    ],
    incomingDate: [
      { required: true, message: "入库日期不能为空", trigger: "blur" }
    ],
    price: [
      { required: true, message: "入库价格不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


/** 查询所有操作人信息并构建映射 */
async function fetchAllOperators() {
  const response = await listUser();
  const doctors = response.rows; 
  console.log("doctors: ", doctors);
  if (doctors && doctors.length > 0) {
    doctors.forEach(doctor => {
      console.log("doctor: ", doctor.nickName);
      operatorMap.value[doctor.userId] = doctor.nickName; 
    });
  }
}

/** 查询所有供应商信息并构建映射 */
async function fetchAllSuppliers() {
  const response = await listSuppliers();
  const suppliers = response.rows; 
  if (suppliers && suppliers.length > 0) {
    suppliers.forEach(supplier => {
      supplierMap.value[supplier.supplierId] = supplier.supplierName;
    });
    supplierList.value = suppliers;
  }
}
/** 查询药品入库信息列表 */
async function getList() {
  loading.value = true;
  await Promise.all([fetchAllOperators(), fetchAllSuppliers()]); // 先获取所有操作人和供应商信息
  const response = await listDrugIncoming(queryParams.value);
  drugIncomingList.value = response.rows;
  total.value = response.total;
  loading.value = false;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    incomingId: null,
    drugName: null,
    drugSpecification: null,
    quantity: null,
    incomingDate: null,
    supplierId: null,
    price: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("drugIncomingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.incomingId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加药品入库信息";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const _incomingId = row.incomingId || ids.value
  const response = await getDrugIncoming(_incomingId);
  form.value = response.data;
  form.value.supplierName = supplierMap.value[form.value.supplierId];
  open.value = true;
  title.value = "修改药品入库信息";
}

/** 提交按钮 */
async function submitForm() {
  proxy.$refs["drugIncomingRef"].validate(async (valid) => {
    if (valid) {
      // 获取当前日期，格式化为 YYYY-MM-DD
      const currentDate = new Date().toISOString().split('T')[0];
      // 将当前日期赋值给表单中的 incomingDate 字段
      form.value.incomingDate = currentDate;
      if (form.value.incomingId != null) {
        // 调用 updateDrugIncoming 函数更新药品入库信息
        updateDrugIncoming(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 如果 incomingId 为空，则是新增操作，调用 listDrugs 函数获取所有药品列表
        const drugList = await listDrugs();
        // 在药品列表中查找是否存在与当前要新增的药品名称和规格都相同的药品
        const existingDrug = drugList.rows.find(drug =>
          drug.drugName === form.value.drugName && drug.drugSpecification === form.value.drugSpecification
        );
        console.log('药品列表:', existingDrug);
        // 如果找到了已存在的药品
        if (existingDrug) {
          try {
            // 根据药品 ID 查询库存信息
            console.log('药品 ID:', existingDrug.drugId);
            const stockResponse = await listDrugStock( {drugId: existingDrug.drugId} );
            console.log('库存信息:', stockResponse);
            const currentStock = parseInt(stockResponse.rows[0].currentQuantity);
            console.log('现有库存数量:', currentStock);
            // 计算新的库存数量，将现有库存数量和本次入库数量相加
            const newStock = currentStock + parseInt(form.value.quantity);
            console.log('新库存数量:', newStock);
            // 根据 drugId 查询 stock_id
            const stockListResponse = await listDrugStock({ drugId: existingDrug.drugId });
            const stockInfo = stockListResponse.rows[0]; // 假设查询结果只有一条库存记录
            console.log('stockInfo:', stockInfo);
            if (!stockInfo) {
              throw new Error('未能找到该药品的库存记录');
            }
            const stockId = stockInfo.stockId;
            // 调用 updateDrugStock 函数更新该药品的库存信息
            await updateDrugStock({
              stockId: stockId,
              currentQuantity: newStock,
              lastIncomingDate: currentDate
            });
            proxy.$modal.msgSuccess("药品库存更新成功");
            // 添加入库信息记录
            try {
              // 这里可以根据实际需求对 form.value 进行调整，如果需要关联 stockId 等信息
              console.log('form.value:', form.value);
              await addDrugIncoming({
                ...form.value
              });
              proxy.$modal.msgSuccess("入库信息记录添加成功");

              // 插入药品变动明细记录
              await addDrugMovements({
                drugId: existingDrug.drugId,
                movementType: 0, // 入库类型
                quantity: form.value.quantity,
                operatorId: currentUserId.value, // 假设表单中有 operatorId 字段
                userId: null, // 根据实际情况填写
                movementDate: currentDate
              });
              proxy.$modal.msgSuccess("药品变动明细记录添加成功");
            } catch (addError) {
              proxy.$modal.msgError("添加入库信息记录失败：" + addError.message);
            }
          } catch (error) {
            proxy.$modal.msgError("更新药品库存失败：" + error.message);
            return;
          }
        } else {
          try {
            // 如果没有找到已存在的药品，先添加药品信息到药品表
            await addDrugs({
              drugName: form.value.drugName,
              drugSpecification: form.value.drugSpecification
            });
            // 根据药品名称和规格再次查询以获取新添加药品的 ID
            const newDrugList = await listDrugs({
              drugName: form.value.drugName,
              drugSpecification: form.value.drugSpecification
            });
            const newDrug = newDrugList.rows.find(drug =>
              drug.drugName === form.value.drugName && drug.drugSpecification === form.value.drugSpecification
            );
            if (!newDrug) {
              throw new Error('未能找到新添加的药品信息');
            }
            const newDrugId = newDrug.drugId;
            // 新增药品库存信息
            await addDrugStock({
              drugId: newDrugId,
              currentQuantity: form.value.quantity,
              lastIncomingDate: currentDate
            });
            // 更新表单中的药品 ID
            form.value.drugId = newDrugId;
            // 调用 addDrugIncoming 函数添加入库信息
            await addDrugIncoming(form.value);
            proxy.$modal.msgSuccess("新增药品、库存及入库信息成功");
            console.log('form.value:', form.value);

            // 插入药品变动明细记录
            await addDrugMovements({
              drugId: newDrugId,
              movementType: 0,
              quantity: form.value.quantity,
              operatorId: currentUserId.value, // 假设表单中有 operatorId 字段
              userId: null, // 根据实际情况填写
              movementDate: currentDate
            });
            proxy.$modal.msgSuccess("药品变动明细记录添加成功");
          } catch (error) {
            proxy.$modal.msgError("新增药品、库存及入库信息失败：" + error.message);
            return;
          }
        }
        // 关闭添加或修改药品入库信息的对话框
        open.value = false;
        // 重新获取药品入库信息列表，更新页面显示
        getList();
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _incomingIds = row.incomingId || ids.value;
  proxy.$modal.confirm('是否确认删除药品入库信息编号为"' + _incomingIds + '"的数据项？').then(function() {
    return delDrugIncoming(_incomingIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/drugIncoming/export', {
    ...queryParams.value
  }, `drugIncoming_${new Date().getTime()}.xlsx`)
}

// 获取操作人姓名的函数
function getOperatorName(operatorId) {
  return operatorMap.value[operatorId] || '未知';
}

// 获取供应商名称的函数
function getSupplierName(supplierId) {
  return supplierMap.value[supplierId] || '未知';
}

// 打开供应商选择对话框
function openSupplierSelectDialog() {
  supplierSelectDialogVisible.value = true;
}

// 选择供应商
function selectSupplier(row) {
  form.value.supplierId = row.supplierId;
  form.value.supplierName = row.supplierName;
  supplierSelectDialogVisible.value = false;
}

// 在组件挂载时获取当前登录用户的 ID
onMounted(async () => {
  try {
    const response = await getInfo();
    console.log('当前登录用户的 ID:', response);
    if (response.code === 200) {
      currentUserId.value = response.user.userId;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
});

getList();
</script>
